package cn.lastcrdg.testitemdecoration;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.blankj.utilcode.util.Utils;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView mRecyclerView;
    private MyAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Utils.init(this);
        mRecyclerView = findViewById(R.id.rv);
        initRecycleView();
        initData();
    }

    /**
     * 初始化数据
     */
    @SuppressLint("CheckResult")
    private void initData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .client(new OkHttpClient())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Api api = retrofit.create(Api.class);
        api.getShowingMovies(20)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<MovieBean>() {
            @Override
            public void accept(MovieBean movieBean) throws Exception {
                mAdapter.setMovieBeans(movieBean.getSubjects());
            }
        });
    }

    /**
     * 初始化列表
     */
    private void initRecycleView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new SticklyItemDecoration(this, new GroupInfoCallback() {
            @Override
            public GroupInfo getGroupInfo(int position) {
                int groupId = position / 2;
                int pos = position % 2;
                GroupInfo groupInfo = new GroupInfo();
                groupInfo.setGroupId(groupId);
                groupInfo.setPosition(pos);
                groupInfo.setItemNum(2);
                return groupInfo;
            }
        }));
        mAdapter = new MyAdapter(this, null);
        mRecyclerView.setAdapter(mAdapter);
    }
}
